package org.budo.support.java.net.util;

import java.util.Comparator;

/**
 * @author limingwei
 */
public class HostInnerFirstComparator implements Comparator<String> {
    public static final Comparator<? super String> INSTANCE = new HostInnerFirstComparator();

    public int compare(String o1, String o2) {
        String index1 = this.prefixValue(o1);
        String index2 = this.prefixValue(o2);

        return index1.compareTo(index2);
    }

    /**
     * 加前缀控制排序 0 -> 48 9 -> 57 a -> 97 z -> 122 A -> 65 Z -> 90
     */
    private String prefixValue(String value) {
        if (null == value) {
            return null;
        }
        if (value.startsWith("192.")) {
            return "000000-" + value;
        }
        if (value.startsWith("172.")) {
            return "000001-" + value;
        }
        if (value.startsWith("10.")) {
            return "000002-" + value;
        }

        if (value.startsWith("127.")) {
            return "999997-" + value;
        }
        if (value.startsWith("0:0:")) {
            return "999998-" + value;
        }
        if (value.length() > "xxx.xxx.xxx.xxx".length()) {
            return "999999-" + value;
        }

        return value;
    }
}